<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/17
 * Time: 11:42
 */

namespace app\api\model;


use app\lib\exception\WorkException;
use app\lib\exception\WorkWordException;
use think\Db;
use think\Exception;
use traits\model\SoftDelete;

class WorkUser extends BaseModel
{
    use SoftDelete;
    protected static $deleteTime = 'delete_time';

    protected $hidden=['delete_time','create_time','update_time'];
    protected $autoWriteTimestamp = true;

    /**
     * 获取器，对获取字段执行默认处理
     * @param $value
     * @return mixed
     */
    public function getUserimgAttr($value)
    {
        $defaultUrl = config('setting.remote_img_url').'goods/15516907460000fNM8kebmEKvL3J7.jpg';
        if(empty($value)){
         $value['url'] = $defaultUrl;
        }
        return $value;
    }

    /**
     * 与work_department多对多关联
     * @return \think\model\relation\BelongsToMany
     */
    public function departments(){
        return $this->belongsToMany('WorkDepartment','workdepartment_workuser','department_id','user_id');
    }

    /**
     * 与user_workuser多对多管连
     * @return \think\model\relation\BelongsToMany
     */
    public function customs(){
        return $this->belongsToMany('User','user_workuser','user_id','wu_id');
    }

    /**
     * 与card_base一对一关联
     * @return \think\model\relation\HasOne
     */
    public function card(){
        return $this->hasOne('CardBase','w_id','id');
    }

    /**
     * 与card_extend一对一关联
     * @return \think\model\relation\HasOne
     */
    public function extend(){
        return $this->hasOne('CardExtend','w_id','id');
    }

    /**
     * 与card_video一对一
     * @return \think\model\relation\HasOne
     */
    public function video(){
        return $this->hasOne('CardVideo','w_id','id');
    }
    /**
     * 与card_browse一对多关联
     * @return \think\model\relation\HasMany
     */
    public function browse(){
        return $this->hasMany('CardBrowse','w_id','id');
    }

    /**
     * 与card_img一对多关联
     * @return \think\model\relation\HasMany
     */
    public function img(){
        return $this->hasMany('CardImg','w_id','id');
    }

    /**
     * t头像1对1
     * @return \think\model\relation\BelongsTo
     */
    public function userimg(){
        return $this->belongsTo('CardImg','head_img','id');
    }
    /**
     * 与third_app一对一关联
     * @return \think\model\relation\BelongsTo
     */
    public function thirdapp(){
        return $this->belongsTo('ThirdApp','t_id','id');
    }

    /**
     * 与user
     * @return \think\model\relation\HasMany
     */
    public function users(){
        return $this->hasMany('UserWorkuser','wu_id','id');
    }

    /**
     * 与order一对多
     * @return \think\model\relation\HasMany
     */
    public function orders(){
        return $this->hasMany('Order','wu_id','id');
    }

    /**
     * 与message一对多
     * @return \think\model\relation\HasMany
     */
    public function fromuser(){
        return $this->hasMany('Message','from_wu_id','id');
    }
    /**
     * 与message一对多
     * @return \think\model\relation\HasMany
     */
    public function touser(){
        return $this->hasMany('Message','to_wu_id','id');
    }

    /**
     * 与Behavior一对多关系
     * @return \think\model\relation\HasMany
     */
    public function behavior(){
        return $this->hasMany('Behavior','wu_id','id');
    }

    /**
     * 获取用户人数
     * @param $uid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getNum($uid){
       return self::withCount(['users'=>function($query)use($uid){
            $query->where('wu_id','=',$uid);
        }])->where('id','=',$uid)->find();
    }

    /**
     * 根据工号获取用户人数
     * @param $t_id
     * @param $user_id 工号
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getNumById($t_id,$user_id){
        return self::where('t_id','=',$t_id)
            ->where('user_id','in',$user_id)
            ->field('id,t_id,user_id,name')
            ->withCount(['users'])
            ->select();
    }

    /**
     * 获取成员列表
     * @param $uid
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserList($uid){
        $user =  self::where("t_id",'=',$uid)
            ->field('id,name,user_id,bind_phone,position,d_id,head_img,ai_power,boss_power')
            ->with(['userimg'])
            ->with(['departments'])
            ->select();
        return $user;
    }
    /**
     * 获取部门成员
     * @param $uid
     * @param $d_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getDepartmentUser($uid,$d_id){
        $user = self::where("a.t_id",'=',$uid)->alias('a')
            ->with(['userimg'])
            ->join('workdepartment_workuser b','b.user_id = a.id')
            ->where("b.department_id = $d_id")
            ->field('a.id,a.name,a.user_id,a.bind_phone,a.position,a.d_id,a.head_img')
            ->with(['departments'=>function($query)use($uid){
                $query->where('t_id','=',$uid);
            }])
            ->select();
        return $user;
    }
    /**
     * 获取成员详情
     * @param $uid
     * @param $userId
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserByID($uid,$userId){
        $user = WorkUser::get(function($query)use($uid,$userId){
            $query->where('t_id','=',$uid)
                ->where('user_id','=',$userId)
                ->with(['card'])
                ->with(['userimg'])
                ->with(['departments'])
                ->with(['img'=>function($query){
                    $query->where('type','=','introduce');
                }]);
        });
        $user->hidden(['t_id','openID','qr_code','ai_power','boss_power']);
        return $user;
    }

    /**
     * 创建人员
     * @param $uid
     * @param $user
     * @return \Exception|int
     */
    public static function createUser($uid,array $user){
        $d_id =$user['d_id'];
        $department_id = WorkDepartment::getDepartmentListByUser($uid,$d_id)->column('id');
        $userInfo = [
            't_id'=>$uid,
            'user_id'=>$user['userId'],
            'bind_phone'=>$user['bind_phone'],
            'gender'=>$user['gender'],
            'name'=>$user['name'],
            'alias'=>isset($user['alias'])?$user['alias']:$user['name'],
            'position'=>$user['position'],
            'style'=>$user['style']
        ];
        Db::startTrans();
        try{
            $workUser = self::create($userInfo);
            $workUser->card()->save(['phone' => $user['phone']]);
            $info = [];
            if (!empty($user['isleader'])){
                foreach ($user['isleader'] as $key=>$value){
                    $info[$key]['isleader'] = $value;
                }
            }
            $workUser->departments()->saveAll($department_id,$info);
            Db::commit();
            return $workUser;
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }

    /**
     * 批量新增
     * @param $uid
     * @param $user
     * @return mixed
     */
    public static function createAllUser($uid,$user)
    {
        foreach ($user as $k=>$v){
            $department = WorkDepartment::where('t_id','=',$uid)
                ->where('d_id','in',$v['d_id'])
                ->column('d_id,name');
            $userInfo = [
                't_id'=>$uid,
                'user_id'=>$v['user_id'],
                'bind_phone'=>$v['phone'],
                'd_id'=>json_encode($department),
                'name'=>$v['name'],
                'position'=>$v['position'],
            ];
            $workUser = self::create($userInfo);
            $workUser->card()->save(['phone' => $v['phone']]);
           $status[] =  $workUser->departments()->saveAll($v['d_id']);
        }
        return $status;
    }

    /**
     * 更新部门成员，其中$user和$d_id不同时为空
     * @param $uid
     * @param null $user
     * @param null $d_id
     * @return WorkUser|int
     * @throws Exception
     */
    public static function updateUser($uid,$user_info=null)
    {
        $userInfo = [
            't_id' => $uid,
            'user_id' => $user_info['userId'],
            'bind_phone' => $user_info['bind_phone'],
            'gender' => $user_info['gender'],
            'name' => $user_info['name'],
            'alias' => isset($user_info['alias']) ? $user_info['alias'] : $user_info['name'],
            'position' => $user_info['position'],
        ];
        $workUser = (new WorkUser)::get($user_info['id']);
        $workUser->save($userInfo);
        //更新card_base表
        if (isset($user_info['email'])) {
            $workUser->card->save(['email' => $user_info['email'], 'phone' => $user_info['phone']]);
        }
        if (isset( $user_info['d_id'])){//更新关系表
            $department = WorkDepartment::where('t_id', '=', $uid)
                ->where('d_id', 'in', $user_info['d_id'])
                ->column('id,name');//获取部门的d_id和名称
            $status =  self::updateDepartment($workUser,$user_info,$department);
        }
        return $status;
    }
    /**
     * 更新部门
     * @param $user
     * @param $department
     * @return $this|int
     */
    public static function updateDepartment($user,$user_info,$department){
        $id = $user->id;
        $d_id = array_keys($department);//当前传递的部门d_id
        foreach ( $user->departments as $depart){
            $result[] = $depart->pivot->department_id;
        }
        if (!empty(array_diff($d_id,$result)) || isset($user_info['isleader'])){
           $condition = ['user_id'=>$id];
            WorkdepartmentWorkuser::where($condition)->delete();//删除原有的关系
            foreach ($d_id as $k=>$v){
               if (isset($user_info['isleader'])){
                   $data[]=[
                       'department_id'=>$v,
                       'user_id'=>$id,
                       'isleader'=>$user_info['isleader'][$k],
                   ];
               }else{
                   $data[]=[
                       'department_id'=>$v,
                       'user_id'=>$id,
                   ];
               }
            }
            $status = (new WorkdepartmentWorkuser)->saveAll($data);//创建新关系
        }
        return $status;
    }
    /**
     * 成员的软删除
     * @param $uid
     * @param $ids
     * @return int
     */
    public static function deleteUser($uid,$ids){
        return WorkUser::destroy(function($query)use($uid,$ids){
                $query->where('t_id','=',$uid)
                    ->where('user_id','in',$ids);
            });
    }

    /**
     * 成员信息更新
     * @param $id
     * @param $data
     * @return $this
     */
    public static function updateUserInfo($id,$data){
        return self::where('id','=',$id)->update($data);
    }
    /**
     * 获取用户详情
     * @param $w_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getUserInfo($w_id){
        $userInfo = WorkUser::with(['card'])
                    ->with(['thirdapp'=>['img']])
                    ->with(['userimg'=>function($query){
                            $query->where('type','=','user')->order('order','asc');
                        }
                    ])
                    ->find($w_id)
                    ->visible(['id','t_id','name','position','qr_code','style','card','userimg','thirdapp']);
        $userInfo->thirdapp->visible(['name','sub_name','head_img']);
      return $userInfo;
    }
    /**
     * 名片拓展信息
     * @param $w_id
     * @return $this
     */
    public static function getExtendInfo($w_id){
        $extendInfo= WorkUser::with(['extend'=>['audio']])
            ->with(['video'])
            ->with([
                'img'=>function($query){
                    $query->where('type','=','introduce')->order('order','asc');
                }])
            ->find($w_id)
            ->visible(['extend','video','img']);
        return $extendInfo;
    }

    /**
     * 获取用户信息
     * @param $t_id
     * @param $userID
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getUser($t_id,$userID){
        return self::where('t_id','=',$t_id)
                ->where('user_id','=',$userID)
                ->find();
    }
    /**
     * 根据成员id获取成员信息
     * @param $wu_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getUserByWuID($wu_id){
        return self::with(['thirdapp'])
            ->with(['userimg'])
            ->where('id','=',$wu_id)
            ->find();
    }

    /**
     * 获取成员基本信息
     * @param $wu_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public  static function getBaseInfo($wu_id){
        $user = WorkUser::with(['card'])
            ->with(['thirdapp'=>['img']])
            ->with(['userimg'=>function($query){
                $query->where('type','=','user')->order('order','asc');
                }
            ])
            ->find($wu_id);
        $user->visible(['id','name','head_img','position','card','thirdapp','userimg']);
        $user->card->hidden(['browsing_num','thumbsup_num']);
//        if ($user->userimg != null){
//            $user->userimg->visible(['url','id']);
//        }
        $user->thirdapp->visible(['sub_name','img']);
        return $user;
    }

    /**
     * 更新图片信息
     * @param $img
     * @param $wu_id
     * @return $this
     */
    public static function updateImg($img,$wu_id){
        $result = self::where('id','=',$wu_id)->update($img);
        return $result;
    }
    /**
     * 名片授权
     * @param $info
     * @param $wu_id
     * @return $this
     */
    public static function authorize($info,$wu_id){
        $data = $info;
        $result = self::where('id','=',$wu_id)->update($data);
        return $result;
    }

    /**
     * 名片的批量授权
     * @param $info
     * @param $list
     * @return $this
     */
    public static function batchAuthorize($info,$list){
        $data = $info;
        $result = self::where('id','in',$list)->update($data);
        return $result;
    }

    /**
     * 授权状态查询
     * @param $t_id
     * @return array
     */
    public static function authorizeStatus($t_id){
        $data= [];
        $data['on'] = self::where('t_id','=',$t_id)
                        ->where('ai_power','=','on')
                        ->field('id,name')
                        ->select();
        $data['off'] = self::where('t_id','=',$t_id)
            ->where('ai_power','=','off')
            ->field('id,name')
            ->select();
        return $data;
    }

    /**
     * 获取子级用户数量
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function getAllUser($id){
            $num = self::where('id','=',$id)->withCount(['users'])->find();
            return $num;
    }

    /**
     * 获取新增用户
     * @param $t_id
     * @param $time
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserNum($t_id,$time){
        $work_user = self::where('t_id','=',$t_id)->column('id');
        $result = UserWorkuser::where('wu_id','in',$work_user)
            ->where('create_time',">=",$time)
            ->field("FROM_UNIXTIME(create_time,'%m-%d') days,count(id) num")
            ->group('days')
            ->select();
        return $result;
    }

    /**
     * 用户数排序
     * @param $t_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserByNum($t_id,$time){
        $result = WorkUser::where('t_id','=',$t_id)
            ->where('ai_power','=','on')
            ->field(['id','name','user_id','head_img','position'])
            ->with(['userimg'=>function($query){
                $query->where('type','=','user')->order('order','asc');
            }
            ])
            ->withCount(['users'=>function($query)use($time){
                    $query->where('create_time','>',$time);
            }])
            ->select();
        return $result;
    }

    /**
     * 订单量
     * @param $t_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserByOrder($t_id,$time){
        $result = WorkUser::where('t_id','=',$t_id)
            ->where('ai_power','=','on')
            ->field(['id','name','user_id','head_img','position'])
            ->with(['userimg'=>function($query){
                $query->where('type','=','user')->order('order','asc');
                }
            ])
            ->withCount(['orders'=>function($query)use($time){
                    $query->where('update_time','>',$time);
            }])
            ->select();
        return $result;
    }

    /**
     * 互动量统计
     * @param $t_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserByInteraction($t_id,$time){
        $result = self::where('t_id','=',$t_id)
            ->where('ai_power','=','on')
            ->field(['id','name','user_id','head_img','position'])
            ->with(['userimg'=>function($query){
                $query->where('type','=','user')->order('order','asc');
            }])
            ->withCount(['fromuser'=>function($query)use($time){
                        $query->where('create_time','>',$time);
            }])
            ->withCount(['touser'=>function($query)use($time){
                        $query->where('create_time','>',$time);
            }])
            ->select();
        return $result;
    }

    /**
     * 成交率统计
     * @param $t_id
     * @param $begin
     * @param $end
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserByRate($t_id,$begin,$end){
        $result = self::where('t_id','=',$t_id)
            ->where('ai_power','=','on')
            ->field(['id','name','user_id','head_img','position'])
            ->with(['userimg'=>function($query){
                $query->where('type','=','user')->order('order','asc');}
            ])
            ->withCount(['users'=>function($query)use($begin,$end){
                $query->where('rate','>=',$begin)->where('rate','<',$end);
            }])
            ->select();
        return $result;
    }

    /**
     *聊天主动性查询
     * @param $t_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getInitiative($wu_id){
        $result = self::where('id','=',$wu_id)
            ->field(['id','name','user_id','head_img','position'])
            ->withCount('fromuser')
            ->withCount('touser')
            ->find();
        return $result;
    }

    /**
     * 活动数量
     * @param $wu_id
     * @param $type
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getWebData($wu_id,$type){
        $result = self::where('id','=',$wu_id)
                    ->withCount(['behavior'=>function($query)use($type){
                        $query->partition([],'user_id',array('type' => 'mod','num' =>4))->where('type','=',$type);
                    }])
                    ->find();
        return $result;
    }

    /**
     * 获取用户数量
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getUserData($wu_id){
        $result = self::where('id','=',$wu_id)
            ->field(['id','name','user_id','head_img','position'])
            ->withCount('users')
            ->find();
        return $result;
    }





    /**
     * 获取行为总数
     * @param $wu_id
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getAllBehavior($wu_id){
        $result = self::where('id','=',$wu_id)
            ->withCount(['behavior'=>function($query){
                $query->partition([],'user_id',array('type' => 'mod','num' =>4))->where('1 = 1');
            }])
            ->find();
        return $result;
    }

    /**
     * 获取所有用户
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getAllUserByStatus($t_id,$time){
        $result = self::where('ai_power','=','on')
            ->where('t_id','=',$t_id)
            ->with(['userimg'=>function($query){
                $query->where('type','=','user')->order('order','asc');}
            ])
            ->withCount(['users'=>function($query)use($time){
                $query->where('create_time','>',$time[0])->where('create_time','<',$time[1]);
            }])->select();
        $result = $result->visible(['id','t_id','name','userimg','position','users_count']);
        return $result;
    }

}